/*
   Copyright 2008, Andres Postiglioni

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package com.aconcagua.mvc.factory {
  import com.aconcagua.beans.BeanDefinitionRegistrar;
  import com.aconcagua.beans.BeanDefinitionSupport;
  import com.aconcagua.beans.ConstructorArg;
  import com.aconcagua.factory.BeanFactory;
  import com.aconcagua.mvc.control.GestureMapping;
  import com.aconcagua.mvc.factory.support.GestureHandler;

  import mx.core.IMXMLObject;

  /**
   * @author Andres Postiglioni
   */
  [DefaultProperty("handler")]
  public class GestureMapping implements BeanDefinitionRegistrar, IMXMLObject{
    private var _id: String;
    private var _mapping: BeanDefinitionSupport;
    private var _gesture: String;
    private var _handler: GestureHandler;
    private var _handlerMethod: String;

    public function GestureMapping() {
      _handlerMethod = "execute";
    }

    public function set gesture(name: String): void {
      _gesture = name;
    }

    public function set handler(gestureHandler: GestureHandler): void {
      _handler = gestureHandler;
    }

    public function set handlerMethod(name: String): void {
      _handlerMethod = name;
    }

    public function initialized(document:Object, id:String): void {
      _id = id;
    }

    public function registerIn(beanFactory: BeanFactory): void {
      //Support for nested commands (no need to declare them outside the mapping):
      if (!_handler.isRegisteredIn(beanFactory)) {
        _handler.registerIn(beanFactory);
      }

      _mapping = new BeanDefinitionSupport(com.aconcagua.mvc.control.GestureMapping, _id);
      _mapping.scope = BeanDefinitionSupport.SCOPE_SINGLETON;
      _mapping.addConstructorArg(new ConstructorArg(_gesture));
      _mapping.addConstructorArg(new ConstructorArg(_handler.id));
      _mapping.addConstructorArg(new ConstructorArg(_handlerMethod));

      beanFactory.registerBeanDefinition(_mapping)
    }

    public function registerAlias(name: String, beanFactory: BeanFactory): void {
      beanFactory.registerAlias(name, _mapping);
    }

    public function isRegisteredIn(beanFactory: BeanFactory): Boolean {
      return _mapping != null && beanFactory.containsBean(_mapping.name);
    }

    public function retrieveFrom(beanFactory: BeanFactory): Object {
      return beanFactory.getBean(_mapping.name);
    }
  }
}